package com.qf.web.filter;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AutoLoginFilter",value = "/index.jsp")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            filterChain.doFilter(request,response);
            return;
        }
        Cookie[] cookies=request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("userInfo")){
                    String userInfo =cookie.getValue();
                    userInfo= Base64Utils.decode(userInfo);
                    String [] arr =userInfo.split("&");
                    if(arr.length==2){
                        String username=arr[0];
                        String password=arr[1];
                        System.out.println(username+"....."+password);
                        UserService userService =new UserServiceImpl();

                        try {
                            User u = userService.login(username, password);
                            request.getSession().setAttribute("user", u);
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(e.getMessage());

                            Cookie deleteCookie =new Cookie("userInfo","");
                            deleteCookie.setPath(request.getContextPath());
                            deleteCookie.setMaxAge(0);
                            response.addCookie(deleteCookie);
                        }
                    }
                }
            }
        }
            filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
